using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Text;

namespace virtuaPol.Util
{
    public class CLogger
    {
        private static object _locker = new object();

        static StreamWriter writer;
        public static bool AllowDebug = true;

        private CLogger()
        { }

        public static void Start(string filename)
        {
            writer = new StreamWriter(filename, true);
            writer.AutoFlush = true;
            WriteLine("Logger started.");
        }

        public static void Stop()
        {
            WriteLine("Logger stopped.");
            writer.Close();
        }

        public static void WriteLine(string line)
        {
            WriteLine(line, false);
        }

        public static void WriteLine(string line, bool debug)
        {
            WriteLine(line, debug, 0);
        }

        private static void WriteLine(string line, bool debug, int layer)
        {
            if (debug && !AllowDebug)
                return;

            if (layer == 0)
                line = DateTime.Now.ToString("G", System.Globalization.DateTimeFormatInfo.InvariantInfo)
                    + " -- " + (debug ? "[DEBUG] " : "") + line;
            else
                for (int i = 0; i < layer; i++)
                    line = "\t" + line;

            lock (_locker)
            {
                writer.WriteLine(line);
            }
        }

        public static void LogError(Exception ex)
        {
            LogError(ex, 0);
        }

        private static void LogError(Exception ex, int layer)
        {
            string line = (layer == 0 ? "ERROR: " : "")
                + "[" + ex.GetType().FullName + "] "
                + ex.Message + " (in " + ex.Source + ":"
                + ex.TargetSite.ReflectedType + ":"
                + ex.TargetSite.Name + ")";
            WriteLine(line, true, layer);
            if (ex.InnerException != null)
                LogError(ex.InnerException, layer++);
        }

    }
}
